package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * 从请求资源路径中解析出请求
 * 如从/test/aaa.do中解析出请求为aaa
 * @author Administrator
 *
 */
public class ParseRequestFilter implements Filter{
	private static Logger log = Logger.getLogger(ParseRequestFilter.class);

	public void destroy() {
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		
		String uri = request.getRequestURI();
		if (log.isDebugEnabled()) {
			log.debug("the request is --> " + uri);
		}
		int index = uri.indexOf(".do");
		if (index < 1) {//请求不正确
			if (log.isDebugEnabled()) {
				log.debug("the request \"" + uri + "\" is invalid");
			}
			request.setAttribute("action", uri);
			request.getRequestDispatcher("/WEB-INF/pages/errors/wrong_request.jsp").forward(request, arg1);
		} else {
			String path = null;//应用名后边的请求路径
			String action = null;
			String subUri = uri.replace(request.getContextPath() + "/", "");
			path = subUri.substring(0, subUri.indexOf("/"));
			action = subUri.substring(subUri.lastIndexOf("/") + 1, subUri.lastIndexOf("."));
			
			if (log.isDebugEnabled()) {
				log.debug("the request \"" + uri + "\" after parsing is --> " + action);
			}
			request.setAttribute("path", path);
			request.setAttribute("action", action);
			arg2.doFilter(request, arg1);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
